<template>
  <el-form-item :rules="item.rule" :label="item.label" :prop="item.prop">
    <el-tag
      v-for="tag in formData[item.prop]"
      :key="tag"
      closable
      :disable-transitions="false"
      @close="handleClose(tag)"
    >
      {{ tag }}
    </el-tag>
    <div class="operation">
      <el-input
        class="input-new-tag"
        v-model="inputValue"
        ref="tagCom"
        size="small"
        @keyup.enter.native="handleInputConfirm"
        @blur="handleInputConfirm"
        placeholder="输入多个时请使用英文分号进行分隔， * 代表模糊匹配"
      >
      </el-input>
      <el-button
        class="button-new-tag"
        type="primary"
        size="small"
        @click="showInput"
        >{{ item.btnText || defaultBtnText }}</el-button
      >
    </div>
  </el-form-item>
</template>

<script>
import _ from "lodash";
import Message from "../../utils/Messager";

export default {
  name: "inputCom",
  props: {
    item: {
      type: Object,
      default: () => {
        return {};
      }
    },
    formData: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      defaultBtnText: "添加",
      inputValue: ""
    };
  },
  methods: {
    handleClose(tag) {
      this.formData[this.item.prop].splice(
        this.formData[this.item.prop].indexOf(tag),
        1
      );
    },
    showInput() {
      this.$nextTick(_ => {
        this.$refs.tagCom.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      if (!this.inputValue || !_.trim(this.inputValue)) {
        Message.warning("请输入内容!");
      } else if (this.formData[this.item.prop].indexOf(this.inputValue) > -1) {
        Message.warning("请勿重复添加!");
      } else {
        const pushValue = this.inputValue.split(",");
        this.formData[this.item.prop] = _.union(
          this.formData[this.item.prop],
          pushValue
        );
      }
      this.inputValue = "";
    }
  }
};
</script>

<style scoped lang="scss">
.el-tag + .el-tag {
  margin-left: 10px;
}

.operation {
  display: flex;

  .input-new-tag {
    flex: 1;
  }

  .button-new-tag {
    height: 32px;
    align-self: center;
  }
}
</style>
